<template>
  <div class="task-tab-container task-card-tab">
    <!-- start 附加组件名称 快速定位 -->
    <div class="card-name-list" v-if="showNameList">
      <span
        :class="{'active': activeTab == card.id }"
        v-for="(card, index) in taskCards"
        :key="index"
        @click="activeTab = card.id"
      >{{ card.name }}</span>
    </div>
    <!-- end 附加组件名称 快速定位 -->
    
    <!-- start 附加组件内容 -->
    <div class="card-info-list" ref="cardLists" v-if="done===2">
      
      <div class="card-info-container" v-for="card in taskCards" :key="card.id" :id="card.id">
      
        <template v-if="activeTab == card.id">
        
          <!-- start 连接器类型的附加组件 -->
          <template v-if="isConnectorCard(card)">
            
            <connector-card-warper
              :card="card"
              :bizId="bizId"
              :share-data="shareData"
              :customer="customer"
              :product="product"
              :isDelete="isDelete"
              :visible="isShowCardTab(card)"
            />
            
          </template>
          <!-- end 连接器类型的附加组件 -->
          
          <!-- start 其他类型的附加组件 -->
          <template v-else>
            
            <!-- start 单次 -->
            <template v-if="card.inputType == 'single'">
              <single-card
                :task="task"
                :cardName='card.name'
                :cardType='cardType'
                :card="card"
                v-bind="$attrs"
                :value="getCardValue(card.id,card.inputType)"
                :task-allow-update="cardAuth"
              />
            </template>
            <!-- end 单次 -->
            
            <!-- start 多次 -->
            <template v-else-if="card.inputType == 'multiple'">
              <multiple-card
                :collapseDirection='collapseDirection'
                :task="task"
                :product="product"
                :cardName='card.name'
                :cardType='cardType'
                :card="card"
                :value="getCardValue(card.id,card.inputType)"
                :task-allow-update="cardAuth"
                :listLoading="listLoading"
              />
            </template>
            <!-- end 多次 -->
            
          </template>
          <!-- end 其他类型的附加组件 -->
        
        </template>
      </div>
    </div>
    
    <!-- 用于查看附件的弹框，由于附件继续隐藏，所以暂时没用，如果要放出附件，或者有其他查看文件的需要，可以放出 -->
    <el-dialog
      width="460px"
      v-if="false"
      class="fileListDialog"
      :visible.sync="fileListDialogShow"
      :title="$t('common.base.checkAttachment')">
      <div class="base-file__preview">
        <base-file-item
          v-for="file in fileList"
          :Source="fileList"
          :file="file"
          readonly
          :key="file.id"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="ghost" @click="fileListDialogShow = false">{{$t('common.base.close')}}</el-button>
      </span>
    </el-dialog>
    <!-- end 附加组件内容 -->
  </div>
</template>

<script>
import * as SettingCusProApi from '@src/api/SettingCusProApi';
/* components */
import SingleCard from './SingleCard';
import MultipleCard from './MultipleCard';
import ConnectorCard from './ConnectorCard';
/* service */
import { isConnectorCard } from '@service/CardService';

/* util */
import * as Utils from '@src/component/form/util';

export default {
  name: 'task-detail-card',
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
    showNameList: {
      type: Boolean,
      default: true
    },
    product: {
      type: Object,
      default: () => ({})
    },
    customerId: {
      type: String,
      default: ''
    },
    isDelete: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeClass: 0,
      taskCards:[],   // 附加组件tab
      cardInfo:[],
      done:0,   // 数据请求完成
      activeTab: '',
      fileList: [],
      fileListDialogShow: false,
      listLoading: true
    }
  },
  provide () {
    return {
      showFilesDialog: this.showFilesDialog
    }
  },
  computed: {
    cardType(){
      return this.shareData.cardType;
    },
    /** 
    * @description 工单详情数据
    */
    task() {
      return this.shareData[this.cardType];
    },
    /** 
    * @description 权限
    */
    cardAuth(){
      return this.shareData.cardAuth;
    },
    collapseDirection() {
      return this.shareData.collapseDirection;
    },
    customer() {
      return this.shareData?.customer || {};
    },
    bizId() {
      return this.customerId || this.product?.id || ''
    }
  },
  methods: {
    isConnectorCard,
    reGetEnabledCardInfo(){
      this.done=0;
      this.getEnabledCardInfo();
      this.getCardInfoByPrimaryId();
      if(this.cardType==='customer') this.$eventBus.$emit('customer_info_record.update_record_list')
      if(this.cardType==='product') this.$eventBus.$emit('product_info_record.update_record_list')
    },
    // 客户产品详情里的组件信息和字段信息列表
    async getEnabledCardInfo(){
      try{
        let {result,code,message}=await SettingCusProApi.getEnabledCardInfo({cardType:this.cardType});
        if(code===0){
          result.forEach(card=>{
            // 多选格式调整
            card.fields = Utils.migration(card.fields || []);
          });
          this.taskCards=result;
          this.done++;
          this.setInitActiveTab()
          // this.addScroll();
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }
    },
    // 详情里获取组件信息集合
    async getCardInfoByPrimaryId(){
      try{
        const params={
          cardType:this.cardType,
          primaryId:this.task.id
        }
        this.listLoading = true;
        let {result,code,message}=await SettingCusProApi.getCardInfoByPrimaryId(params);
        if(code===0){
          this.cardInfo=result;
          this.done++;
          // this.addScroll();
          this.setInitActiveTab()
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }finally {
        this.listLoading = false;
      }
    },
    // 设置activeTab初始值
    setInitActiveTab () {
      if (this.done === 2 && this.taskCards.length && this.activeTab === '') {
        this.activeTab = this.taskCards[0].id;
      }
    },
    /** 
    * @description 获取指定附加组件数据
    */
    getCardValue(id,inputType) {
      let value=this.cardInfo.filter(card => card.cardId == id)[0];
      if(inputType==='single' && value && Array.isArray(value.attribute)){
        value.attribute=value.attribute[0];
      }
      return value
    },
    showFilesDialog (fileList) {
      this.fileList = fileList
      this.fileListDialogShow = true
    },
    isShowCardTab(card) {
      return this.activeTab.includes(card?.id)
    }
  },
  mounted() {
    this.getEnabledCardInfo();
    this.getCardInfoByPrimaryId();
    this.$eventBus.$on('customer_card_delete', this.reGetEnabledCardInfo);
    this.$eventBus.$on('product_card_delete', this.reGetEnabledCardInfo)
  },
  beforeDestroy(){
    this.$eventBus.$off('customer_card_delete', this.reGetEnabledCardInfo);
    this.$eventBus.$off('product_card_delete', this.reGetEnabledCardInfo)
  },
  components: {
    [SingleCard.name]: SingleCard,
    [MultipleCard.name]: MultipleCard,
    [ConnectorCard.name]: ConnectorCard,
    ConnectorCard,
  }
}
</script>

<style lang="scss">
.task-card-tab {
  height: 100%;
  padding: 0 !important;
  background: $bg-color-l1;
  overflow: hidden;

  display: flex;
  flex-direction: column;

  // 附加组件名称
  .card-name-list {
    padding: 12px 12px 8px;
    background-color: #fff;
    border-bottom: 1px solid $bg-color-l1;

    span {
      color: $text-color-regular;
      margin: 0 20px 4px 0;
      display: inline-block;

      &:hover {
        color: $text-color-primary;
        cursor: pointer;
      }
      &.active {
        color: $color-primary;
      }
    }
  }

  // 附加组件内容
  .card-info-list {
    flex: 1;
    overflow: auto;
    // margin-bottom: 80px;
    // height: 100%;

    .card-info-container {
      background-color: #fff;
      border-radius: 4px;

      // &:not(:first-child) {
      //   margin-top: 12px;
      // }

      .card-name {
        padding: 12px 12px 0 34px;
        color: $text-color-primary;
        font-size: $font-size-base;
        font-weight: 500;

        background: url(../../../../../assets/img/task/card_icon.png) no-repeat 12px 15px;
        background-size: 14px 14px;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
  .base-file__preview {
    max-height: 300px;
    overflow: auto;
  }
  ::v-deep .cur-point {
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>